/*
 * @Author: 码农 2646995216@qq.com
 * @Date: 2025-02-20 22:48:56
 * @LastEditors: 码农 2646995216@qq.com
 * @LastEditTime: 2025-02-22 22:04:49
 * @FilePath: /shm/comm.hpp
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
#pragma once
#include <sys/types.h>
#include <sys/ipc.h>
#include<iostream>
#include<string.h>
#include <sys/shm.h>
#define SIZE 4048

using namespace std;
const char* pathname="/home/CH1/shm";//随便命名，但一般是文件的位置
const int proj_id=0x112233;

//获得唯一的key值
key_t GetShmKey()
{
	key_t key=ftok(pathname,proj_id);//成功，返回唯一的key值，失败，返回-1
	if(key<0)
	{
		cout<<"ftok error,error:"<<errno<<",error strinng:"<<strerror(errno)<<endl;
		exit(1);//直接退出
	}
	return key;
}

int Shmid(key_t key,size_t size,int shmflg)
{
	int shmid=shmget(key,size,shmflg);//成功，返回唯一的shmid值，失败，返回-1
	if(shmid<0)
	{
		cout<<"shmget error,error:"<<errno<<",error string:"<<strerror(errno)<<endl;
		exit(1);
	}
	return shmid;
}

//创建内存池，并返回唯一的shmid值
int CreateShmid(key_t key,size_t size)
{
	return Shmid(key,size,IPC_CREAT | IPC_EXCL | 0666);// 没有就创建，有就报错，权限666
}

//内存池已经存在，返回唯一的shmid值
int GetShmid(key_t key,size_t size)
{
	return Shmid(key,size,IPC_CREAT);// 不存在则创建，存在的话直接获取
}

//将内存池与地址空间进行挂接
void* GetShmaddr(int shmid)
{
	void* shmaddr=shmat(shmid,NULL,0);//后面两个参数一般是默认的
	if(shmaddr<0)
	{
		cout<<"shmid error:"<<errno<<",error string:"<<strerror(errno)<<endl;
		exit(1);
	}
    return shmaddr;
}

//取消挂接
void ShmDel(const void* shmaddr)
{
	int n=shmdt(shmaddr);

}

//删除共享内存
void DeleteShm(int shmid)
{
    int n = shmctl(shmid, IPC_RMID, nullptr);
    if (n == -1)
    {
        cerr << "shmctl error" << errno << endl;
    }
    else
    {
        cout << "delete successfully" << endl;
    }
}
